package com.aneliya.server.tcp;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import com.aneliya.client.IClientFactory;
import com.aneliya.client.tcp.TCPClient;
import com.aneliya.server.IServerImpl;
import com.aneliya.server.dispatcher.Dispatcher;

public class TCPServerImpl implements IServerImpl, ITCPServer {
	private ServerSocket serverSocket;
	
	private IClientFactory clientFactory;
	public void setClientFactory(IClientFactory clientFactory) {
		this.clientFactory = clientFactory;
	}
	
	private Dispatcher dispatcher;
	public void setDispatcher(Dispatcher dispatcher) {
		this.dispatcher = dispatcher;
	}

	
	public void start() {
		try {
			serverSocket = new ServerSocket(listeningPort);
			System.out.println("Chat server started on port " + listeningPort);
			
			dispatcher.start();
			
			handleClientConnections();
		} catch (IOException ex) {
			System.err.println("Chat server can't start on port " + listeningPort);
			ex.printStackTrace();
			System.exit(-1);
		}
	}

	public void stop() {
		// TODO Implement method
	}

	private int listeningPort;
	public void setListeningPort(int listeningPort) {
		this.listeningPort = listeningPort;
	}

	public void handleClientConnections() {
		try {
			while (true) {
				Socket socket = serverSocket.accept();
				TCPClient client = (TCPClient) clientFactory.createClient(socket);
				client.start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
